using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace Starznet.SharePoint.SPDAT.ApplicationPages.Settings
{
    public class AddEditHandlerPage : LayoutsPageBase
    {
        private enum HandlerTypes
        {
            Item, Web, Site
        }

        protected TextBox TxtAssemblyName;
        protected TextBox TxtAssemblyVersion;
        protected TextBox TxtAssemblyCulture;
        protected TextBox TxtPublicKeyToken;
        protected TextBox TxtClass;
        protected DropDownList DdlEventType;

        private SPList _oList;
        private SPList List
        {
            get
            {
                if (_oList == null)
                {
                    Guid oListGUID = new Guid(Request.QueryString["List"].ToString());
                    _oList = SPContext.Current.Web.Lists[oListGUID];
                }
                return _oList;
            }
        }

        private HandlerTypes HandlerType
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString.Get("List")))
                    return HandlerTypes.Item;

                return HandlerTypes.Web;
            }
        }

        public override string PageToRedirectOnCancel
        {
            get
            {
                string sUrl = "ManageEventHandlers.aspx";
                if (!string.IsNullOrEmpty(Request.QueryString.Get("List")))
                    sUrl += "?List=" + Request.QueryString.Get("List");

                return sUrl;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!IsPostBack) 
                PopulateEventTypes(this.HandlerType);
            
            if (Request.QueryString["Handler"] != null && !IsPostBack)
            {
                SPEventReceiverDefinition oEvent = GetEventReceiver(new Guid(Request.QueryString["Handler"].ToString()));

                string[] sAssembly = oEvent.Assembly.Split(',');
                this.TxtAssemblyName.Text = sAssembly[0].Replace(" ","").Replace("Assembly=","");
                this.TxtAssemblyVersion.Text = sAssembly[1].Replace(" ", "").Replace("Version=", "");
                this.TxtAssemblyCulture.Text = sAssembly[2].Replace(" ", "").Replace("Culture=", "");
                this.TxtPublicKeyToken.Text = sAssembly[3].Replace(" ", "").Replace("PublicKeyToken=", "");
                this.TxtClass.Text = oEvent.Class;
                this.DdlEventType.SelectedValue = oEvent.Type.ToString();
            }
        }

        protected void BtnUpdate_Click(object Sender, EventArgs e)
        {
            String sAssembly = this.TxtAssemblyName.Text +
                                ", Version=" + this.TxtAssemblyVersion.Text +
                                ", Culture=" + this.TxtAssemblyCulture.Text +
                                ", PublicKeyToken=" + this.TxtPublicKeyToken.Text;

            if (Request.QueryString["Handler"] != null)
            {
                //Editing an existing event handler
                SPEventReceiverDefinition oEvent = GetEventReceiver(new Guid(Request.QueryString["Handler"].ToString()));
                oEvent.Delete();
            }

            //Add a new one
            switch (this.HandlerType)
            {
                case HandlerTypes.Item:
                    List.EventReceivers.Add(
                        (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), this.DdlEventType.SelectedValue),
                        sAssembly, 
                        this.TxtClass.Text);
                    break;
                case HandlerTypes.Web:
                    SPContext.Current.Web.EventReceivers.Add(
                        (SPEventReceiverType)Enum.Parse(typeof(SPEventReceiverType), this.DdlEventType.SelectedValue),
                        sAssembly, 
                        this.TxtClass.Text);
                    break;
            }

            Response.Redirect(this.PageToRedirectOnCancel);
        }

        private SPEventReceiverDefinition GetEventReceiver(Guid eventGuid)
        {
            switch (this.HandlerType)
            {
                case HandlerTypes.Item:
                    return List.EventReceivers[eventGuid];
                case HandlerTypes.Web:
                    return SPContext.Current.Web.EventReceivers[eventGuid];
            }
            return null;
        }

        private void PopulateEventTypes(HandlerTypes handlerType)
        {
            string sRestrict = handlerType.ToString();
            foreach (string sVal in Enum.GetNames(typeof(SPEventReceiverType)))
            {
                if (sRestrict == "Item" && !sVal.StartsWith(sRestrict))
                    continue;

                DdlEventType.Items.Add(new ListItem(Utility.SplitCasedString(sVal), sVal));
            }
        }
    }
}
